package com.cheng.admin.controller;


import cn.dev33.satoken.annotation.SaCheckRole;
import cn.dev33.satoken.stp.StpUtil;
import com.cheng.admin.model.Order;
import com.cheng.admin.service.OrderService;
import com.cheng.common.annotation.JWTIgnore;
import com.cheng.common.domain.BaseSearchVO;
import com.cheng.common.domain.R;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

/**
 * <p>
 * 订单 前端控制器
 * </p>
 *
 * @author 起凡
 * @since 2022-01-17
 */
@RestController
@RequestMapping("/order")
@Slf4j
public class OrderController {
    @Autowired
    OrderService orderService;


    @GetMapping("list")
    public R<PageInfo<Order>> list(BaseSearchVO baseSearchVO) {
        baseSearchVO.setUserId(StpUtil.getLoginIdAsLong());

        return R.ok(orderService.listOrder(baseSearchVO));
    }

    @GetMapping("get")
    public R<Order> get(@RequestParam Long id) {
        return R.ok(orderService.get(id));
    }

    /**
     * 订单支付回调 <br/>
     * 用户在小程序内支付完之后，微信服务器会向后端发送支付成功消息 <br/>
     * <span>@JWTIgnore</span> 代表不需要权限校验
     *
     * @param request
     * @return
     * @throws Exception
     */
    @JWTIgnore
    @PostMapping("notify")
    public String notify(HttpServletRequest request) throws Exception {
        return orderService.callBack(request);
    }


    @PostMapping("create")
    public R<Order> create(@RequestBody @Validated Order order) {
        log.info(order.toString());
        return R.ok(orderService.create(order));
    }


    @GetMapping("pay")
    public R<String> pay(@RequestParam Long id) throws Exception {
        return R.ok(orderService.pay(id));
    }

    @GetMapping("confirm")
    public R<Boolean> confirm(@RequestParam Long id) {
        orderService.confirm(id);
        return R.ok(true);
    }

    @GetMapping("cancel")
    public R<Boolean> cancel(@RequestParam Long id) {
        orderService.cancel(id);
        return R.ok(true);
    }

    /**
     * 发货
     *
     * @param logisticsNo 物流单号
     * @param id          订单id
     * @return
     */
    @SaCheckRole("admin")
    @GetMapping("ship")
    public R<Boolean> ship(@RequestParam String logisticsNo, @RequestParam Long id) {
        orderService.ship(id, logisticsNo);
        return R.ok(true);
    }


    /**
     * 后台管理页面查看订单
     *
     * @param baseSearchVO
     * @return
     */
    @GetMapping("back/list")
    @SaCheckRole("admin")
    public R<PageInfo<Order>> listForBack(BaseSearchVO baseSearchVO) {
        return R.ok(orderService.listOrder(baseSearchVO));
    }
}

